package com.sunlands.qdcy.tongzhuo.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.sunlands.qdcy.tongzhuo.exception.BusinessException;
import com.sunlands.qdcy.tongzhuo.exception.SendExceptionUtil;
import com.sunlands.qdcy.tongzhuo.feign.vo.UserInfoDTO;
import com.sunlands.qdcy.tongzhuo.feign.*;
import com.sunlands.qdcy.tongzhuo.vo.BusinessResult;
import com.sunlands.qdcy.tongzhuo.constant.CommonResultMessage;
import com.sunlands.qdcy.tongzhuo.vo.GroupSimpleVO;
import com.sunlands.qdcy.tongzhuo.vo.UserFriendVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangxiaobin
 * @title: BaseService
 * @description: TODO
 * @date 2019/4/2516:40
 */
@Slf4j
public class BaseService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserCenterService userCenterServer;
    @Autowired
    protected SendExceptionUtil sendExceptionUtil;
    @Autowired
    protected MessageService messageService;
    @Autowired
    protected UserFriendClient userFriendClient;
    @Autowired
    protected GroupClient groupClient;

    //构建PageRequest
    protected PageRequest buildPageRequest(int pageNumber, int pagzSize, Sort sort) {
        return new PageRequest(pageNumber - 1, pagzSize, sort);
    }

    protected UserInfoDTO getUserById(Long userId) {
        if (userId == null || userId.intValue() == 0) {
            return null;
        }
        try {
            BusinessResult<UserInfoDTO> businessResult = userCenterServer.getUserInfoById(userId);
            if (businessResult.getCode().longValue() == CommonResultMessage.SUCCESS.code) {
                return businessResult.getData();
            } else {
                log.error("获取用户信息失败，id = {} , res = {} ", userId, JSON.toJSONString(businessResult));
                sendExceptionUtil.sendException("调用户系统查询用户失败" + userId, new UsernameNotFoundException("" + userId));
            }
        } catch (Exception ex) {
            log.error("获取用户信息失败，id = {} , ex = {} ", userId, ex);
            sendExceptionUtil.sendException("调用户系统查用户异常" + ex.getMessage(), new UsernameNotFoundException("" + userId));
        }
        return null;
    }

    /**
     * 根据用户id列表，获取用户列表
     *
     * @param userIds
     * @return
     */
    protected List<UserInfoDTO> listByIds(Collection<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return null;
        }

        try {

            BusinessResult<List<UserInfoDTO>> result = userCenterServer.list(Lists.newArrayList(userIds));

            if (result.getCode().longValue() == CommonResultMessage.SUCCESS.code) {
                return result.getData();
            } else {
                log.error("获取用户信息失败，id = {} , res = {} ", userIds, JSON.toJSONString(result));
                sendExceptionUtil.sendException("调用户系统查询用户失败" + userIds, new UsernameNotFoundException("调用户系统查询用户失败"));
            }
        } catch (Exception ex) {
            log.error("获取用户信息失败，id = {} , ex = {} ", userIds, ex);
            sendExceptionUtil.sendException("调用户系统查用户异常" + ex.getMessage(), ex);
        }
        return null;
    }

    /**
     * 根据用户userId统一查询用户列表，并按userId分类
     *
     * @param userIds
     * @return
     */
    protected Map<Long, UserInfoDTO> mapByIds(Collection<Long> userIds) {
        Map<Long, UserInfoDTO> userMap = new HashMap();

        List<UserInfoDTO> users = listByIds(userIds);
        if (CollectionUtils.isEmpty(users)) {
            return userMap;
        }

        userMap = users.stream().collect(Collectors.toMap(UserInfoDTO::getId, u -> u, (u1, u2) -> u1));

        return userMap;
    }


    protected List<UserFriendVO> userFriendsList(Long userId) {
        if (userId == null || userId == 0) {
            log.error("查询道友列表，userId为空！");
            return null;
        }
        BusinessResult resultVO = null;
        List<UserFriendVO> list = Lists.newArrayList();
        try {
            long t1 = System.currentTimeMillis();

            resultVO = userFriendClient.userFriendsList(userId);
            long t2 = System.currentTimeMillis();
            log.debug("查询道友列表cost:{}ms，userId={},resultVO={}", t2 - t1, userId, JSON.toJSONString(resultVO));
            if (resultVO == null
                    || resultVO.getCode() == null
                    || resultVO.getCode().longValue() != CommonResultMessage.SUCCESS.code) {
                String r = JSON.toJSONString(resultVO);
                log.error("查询道友列表失败，cost:{}ms，userId={},resultVO={}", t2 - t1, userId, r);
                sendExceptionUtil.sendException("查询道友列表失败userId=" + userId + " result=" + r, new UsernameNotFoundException("查询道友列表失败userId"));
                throw new BusinessException("查询道友列表失败：userId=" + userId);
            }

            if (resultVO.getData() != null) {
                list = JSON.parseArray(JSON.toJSONString(resultVO.getData()), UserFriendVO.class);
            }
        } catch (Exception e) {
            sendExceptionUtil.sendException("查询道友列表失败userId=" + userId + " result=" + JSON.toJSONString(resultVO), new UsernameNotFoundException("查询道友列表失败userId"));
            log.error("查询道友列表失败，userId={},resultVO={},e={}", userId, JSON.toJSONString(resultVO), e);
        }
        return list;
    }

    /**
     * 获取用户useId所加入的群
     *
     * @param userId
     * @return
     */
    protected List<GroupSimpleVO> getGroupList(Long userId) {
        if (userId == null || userId == 0) {
            return null;
        }
        BusinessResult<List<GroupSimpleVO>> result = null;

        try {
            long t1 = System.currentTimeMillis();
            result = groupClient.getSimpleGroupList(userId, userId);
            long t2 = System.currentTimeMillis();

            if (result == null
                    || result.getCode() == null
                    || result.getCode().longValue() != CommonResultMessage.SUCCESS.code) {
                String r = JSON.toJSONString(result);
                log.error("查询群列表失败，cost:{}ms，userId={},resultVO={}", t2 - t1, userId, r);
                sendExceptionUtil.sendException("查询群列表失败userId=" + userId + " result=" + r, new BusinessException("查询群列表失败userId"));
                throw new BusinessException("查询群列表失败：userId=" + userId);
            }
            return result.getData();

        } catch (Exception e) {
            sendExceptionUtil.sendException("查询群列表失败userId=" + userId + " result=" + JSON.toJSONString(result), e);
            log.error("查询道友列表失败，userId={},resultVO={},e={}", userId, JSON.toJSONString(result), e);
        }

        return null;
    }


}
